<?php

class Application_Model_DesktopMapper{

	protected $_dbTable;

	public function setDbTable($dbTable)
	{
		if (is_string($dbTable)) {
			$dbTable = new $dbTable();
		}
		if (!$dbTable instanceof Zend_Db_Table_Abstract) {
			throw new Exception('Invalid table data gateway provided');
		}
		$this->_dbTable = $dbTable;
		return $this;
	}

	public function getDbTable()
	{
		if (null === $this->_dbTable) {
			$this->setDbTable('Application_Model_DbTable_Desktop');
		}
		return $this->_dbTable;
	}
	
	public function save(Application_Model_Desktop $desktop){
	
		
	
		$computerMapper = new Application_Model_ComputerMapper();
		$row = $computerMapper->save($desktop);
		$desktop->setComputerId($row);
	
		$data = array(
				'id_computer' 		=> $desktop->getComputerId(),
		);
	
		if (null === ($id = $desktop->getDesktopId())) {
			unset($data['id_desktop']);
			return $this->getDbTable()->insert($data);
		} else {
			$this->getDbTable()->update($data, array('id_desktop = ?' => $id));
			return $id;
		}
	}
	
	public function find($id, Application_Model_Desktop $desktop)
	{
		$result = $this->getDbTable()->find($id);
		if (0 == count($result)) {
			return;
		}
		$row = $result->current();
		$desktop->setDesktopId($row->id_desktop);
		$desktop->setComputerId($row->id_computer);
	
		$computerMapper = new Application_Model_ComputerMapper();
		$desktop = $computerMapper->find($desktop->getComputerId(), $desktop);
	
		return $desktop;
	}
	
	public function delete($id)
	{
	
		$desktop= new Application_Model_Desktop();
		$computerMapper = new Application_Model_ComputerMapper();
		$desktop = $this->find($id, new Application_Model_Desktop());
	
		$result = $this->getDbTable()->find($id);
		if (0 != count($result)) {
			$this->getDbTable()->delete(array('id_desktop = ?' => $id));
		}
	
		$computerMapper->delete($desktop->getComputerId());
	
	
	}
	
	public function indexBuilder(Zend_Search_Lucene_Document $doc, Application_Model_Desktop $desktop)
	{
		$computerMapper = new Application_Model_ComputerMapper();
		$doc->addField(Zend_Search_Lucene_Field::Text('objectType', 'desktop', 'utf-8'));
		$doc = $computerMapper->indexBuilder($doc, $desktop);
		
		return $doc;
	}
}